am4core.ready(function() {

  // 主题
  am4core.useTheme(am4themes_dark);
  am4core.useTheme(am4themes_animated);

  // 生成地图实例
  var chart = am4core.create("chartdiv", am4maps.MapChart);

  // 声明使用版本
  chart.geodata = am4geodata_worldLow;

  chart.geodataNames = am4geodata_lang_cn_ZH;

  // 设置地图经纬模式
  chart.projection = new am4maps.projections.Miller();

  // 输入地图定位点
  var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries());


  // 根据数据载入地图
  polygonSeries.useGeodata = true;


  // 设置激活位置样式
  var polygonTemplate = polygonSeries.mapPolygons.template;
  polygonTemplate.applyOnClones = true;
  polygonTemplate.togglable = true;
  polygonTemplate.tooltipText = "{name}";
  
  polygonTemplate.nonScalingStroke = true;
  polygonTemplate.strokeOpacity = 0.5;
  polygonTemplate.fill = am4core.color("#777");

  // 设置 active 与 hover 颜色
  var ss = polygonTemplate.states.create("active");
  ss.properties.fill = am4core.color("#f8db53");

  var hs = polygonTemplate.states.create("hover");
  hs.properties.fill = am4core.color("#c1c655");

  // Hide Antarctica
  polygonSeries.exclude = ["AQ"];


  // 获得印度
  // var india = polygonSeries.getPolygonById("IN");


  // 小工具栏
  // 大小缩放
  var zoomControl = new am4maps.ZoomControl();
  chart.zoomControl = zoomControl;
  chart.zoomControl.align = "left";

  // 复位键
  function reset_map() {
    chart.goHome();
    lastSelected.isActive = false;
    chart.deltaLongitude = 0;
    $('select').val('default');
    $('select').selectpicker('refresh');
  };

  // home 键
  var homeButton = new am4core.Button();
  homeButton.events.on("hit", function(){
    reset_map()
  });

  // 同时让title 也具备和 home一样的回退功能
  $("#icon").click(function(argument) {
    reset_map()
  });

  homeButton.icon = new am4core.Sprite();
  homeButton.padding(7, 5, 7, 5);
  homeButton.width = 30;
  homeButton.icon.path = "M16,8 L14,8 L14,16 L10,16 L10,10 L6,10 L6,16 L2,16 L2,8 L0,8 L8,0 L16,8 Z M16,8";
  homeButton.marginBottom = 10;
  homeButton.parent = chart.zoomControl;
  homeButton.insertBefore(chart.zoomControl.plusButton);

  // 地图偏移
  chart.deltaLongitude = 0;

  // 大地图禁用拖拽
  chart.panBehavior = "none";
  chart.events.on("zoomlevelchanged", function(){
    // queue event loop so a final zoomlevelchanged can be "cauight"
    setTimeout(
      function() {
        if (chart.zoomLevel <= 1.5) {
          chart.panBehavior = "none";
        } else if (chart.zoomLevel > 1.5) {
          chart.panBehavior = "move";
        }
      }, 0);
  });

  // 俄罗斯与新西兰数据修正
  polygonSeries.data = [{
     "id": "NZ",
     "zoomLevel": 12,
     "zoomGeoPoint": {
     "latitude": -41,
     "longitude": 173
   }
  }, {
   "id": "RU",
   "zoomLevel": 2.5,
   "zoomGeoPoint": {
     "latitude": 62,
     "longitude": 96
   }
  }];

  polygonSeries.dataFields.zoomLevel = "zoomLevel";
  polygonSeries.dataFields.zoomGeoPoint = "zoomGeoPoint";



  // 设置右弹出
  var countrySlider = new mSlider({
      dom: ".layer-right",
      direction: "right",
      distance: "22rem"
  });

  // 插入对应国家信息
  var insertCountryData = function(data) {
    // 国旗
    $("#country_flag").attr({src:data["nationalflag"]});
    // 中文名
    $("#country_name").html(data["name"]);
    // 中文全名
    $("#country_cname").html(data["cname"]);
    // 英文
    $("#country_en_name").html(data["ename"]);
    // gdp
    $("#gdp").html(data["gdp"]);
    // 人均gdp
    $("#avggdp").html(data["avggdp"]);
    // 货币
    $("#currency").html(data["currency"]);
    // 人口
    $("#population").html(data["population"]);
    // 宗教
    $("#mainreligion").html(data["mainreligion"]);
    // 政治体制
    $("#political").html(data["political"]);
    // 首都
    $("#capital").html(data["capital"]);
    // 主要城市
    $("#maincity").html(data["maincity"]);

    // 修正国旗链接问题
    if (data["nationalflag"] == null) {
      $("#country_flag").attr({src:""});
    }
    // 将所有无值节点替换成 --
    var arr = $("dd"); 
    for (i = 0; i < arr.length; i++) {
      if (arr[i].innerText == "") {
        arr[i].textContent = "--"
      }
    }
  }

  // 显示弹出
  var showSideBar = function(data) {
    // 注入数据
    insertCountryData(data)
    // 右边框弹出
    countrySlider.open();
  };


  // 显示国家信息
  var showCountryJsonInfo = function(country_name){
    $.getJSON("data/" + country_name + ".json",function(data){
      // console.log(data);
      // 展开 slider信息
      showSideBar(data);
    });
  };
  
  var lastSelected;
  var hit_lock = true;

  // 点击地图事件
  polygonTemplate.events.on("hit", function(ev) {
    if (lastSelected) {
      lastSelected.isActive = false;
    }
    ev.target.series.chart.zoomToMapObject(ev.target);
    // console.log(ev.target);
    if (lastSelected !== ev.target) {
      lastSelected = ev.target;
    }
    countryInfo = lastSelected.dataItem.dataContext;
    
    hit_lock = false;
    // select 时刻需要改变 select 值, 但同时需要避免触发 select 带来的影响
    $('select').selectpicker('val', countryInfo.id);
    hit_lock = true;
    showCountryJsonInfo(countryInfo.id);
  })

  // 输入 select 事件
  $('select').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
    if (hit_lock) {

      // 获得 select指定国家
      country_id = countries[clickedIndex-1].id
      target_country = polygonSeries.getPolygonById(country_id);

      // 被选中国家聚焦
      if (lastSelected) {
        lastSelected.isActive = false;
      }
      target_country.series.chart.zoomToMapObject(target_country);
      console.log(target_country);
      if (lastSelected !== target_country) {
        lastSelected = target_country;
        lastSelected.isActive = true;
      }
      countryInfo = lastSelected.dataItem.dataContext;
      // console.log(countryInfo.name + "(" + countryInfo.id + ")");
      showCountryJsonInfo(countryInfo.id);

    }
  });

}); // end am4core.ready()